<template>
  <s-layout :tabbarshow="false" id="layout" navbar="normal" :title="`修改拜访`" :autoBack="true" leftIconColor="$uni-text-color"
    :bgColor="'rgba(0,0,0,0)'" :titleStyle="{ color: '#fff', fontSize: '32rpx' }">

    <view class="container"
      :style="{ backgroundImage: `url( ${baseUrl}/uploads/uniapp_image/staff/staff_project_arrange.png)`, paddingTop: (safeAreaInsets?.top + 44) + 'px' }">

      <!-- 表单盒子 -->
      <view class="form_box area">
        <scroll-view scroll-y :enable-back-to-top="true" class="comprehensive">
          <!-- 表单结构 -->
          <uni-forms ref="relRef" v-model="state.formData" :rules="state.rules" validateTrigger="bind" labelWidth="120">
            <uni-forms-item name="realName" label="拜访人姓名：" required>
              <uni-easyinput placeholder="请输入姓名" v-model="state.formData.realName" :inputBorder="false" >
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="mobile" label="拜访人号码：" required>
              <uni-easyinput placeholder="请输入手机号码" v-model="state.formData.mobile" type="number" :inputBorder="false" >
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="company" label="拜访公司名称：" required>
              <uni-easyinput placeholder="请输入公司地址" v-model="state.formData.company" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="address" label="拜访公司地址：" required>
              <uni-easyinput placeholder="请输入公司地址" v-model="state.formData.address" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="reason" label="拜访事由：" required>
              <uni-easyinput placeholder="请输入拜访事由" v-model="state.formData.reason" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <view class="cards">
              <view class="title">
                图片:
              </view>
              <view class="img">
                <up-upload :fileList="state.fileList1" @afterRead="imageUpload" @delete="deletePic" name="4" multiple
              :maxCount="4"   :previewFullImage="true"></up-upload>
              </view>
            </view>
          </uni-forms>

        </scroll-view>
      </view>

    </view>

  </s-layout>

  <!-- 底部提交按钮 -->
  <view v-if="!editid">
    <s-button @netWork="submitForm" :text="text" ></s-button>
  </view>

  <view v-else class="edit_button">
    <button class="del" @tap="deletesubmit">删除</button>
    <button class="edit" @tap="editsubmit">保存修改</button>
  </view>
  <up-modal :show="delete_show" :showCancelButton="true" @confirm="delete_confirm" @cancel="delete_cancel" :content="'您确定要删除这条数据么？'"></up-modal>
</template>

<script setup>
import sheep from '@/sheep';
import { ref, reactive, unref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { baseUrl } from "@/sheep/config";
import { realName, mobile, address, reason, company } from '@/sheep/validate/form';


const { safeAreaInsets } = uni.getSystemInfoSync();
const text = ref("提交");
const state = reactive({
  fileList1: [],
  formData: {
    realName: '',
    mobile: '',
    company: '',
    address: '',
    reason: '',
    uploadimg:''

  },
  rules: {
    realName,
    mobile,
    address,
    company,
    reason
  },
});
const  editid = ref('')

onLoad((options)=>{
  if(options.id){
    editid.value = options.id
    getview()
  }

})

// 请求详情
const getview = ()=>{
  let parpam ={
    ids:editid.value 
  }
  sheep.$api.visit_record.getVisitRecordView(parpam).then((res) => {
    if(res.code == 1){
      state.formData.realName = res.data.name
      state.formData.mobile = res.data.phone
      state.formData.company = res.data.company
      state.formData.address = res.data.address
      state.formData.reason = res.data.content
      const item= res.data.images.split(',')
      if(res.data.images){
        item.forEach((a,index)=>{
          state.fileList1?.push({
            url:`${baseUrl}`+a
          })      
          postData.value.push(a)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
        }) 
        // console.log(state.fileList1,'默认返回图片')
      }
    }
  })
}
const relRef = ref();
const indexss =ref(true)
const submitForm = async () => {
  state.formData.uploadimg = postData.value.join(',')
  const validate = await unref(relRef)
    .validate()
    .catch((error) => {
    });
  if (!validate) return;
  if (state.fileList1 == '') {
		uni.showToast({
			title: '请上传图片',
			icon: 'none',
			duration: 1000
		})
		return false
	}
  uni.$u.throttle(() => {
  let parpam={
    name: state.formData.realName,
    phone: state.formData.mobile,
    company: state.formData.company,
    content: state.formData.reason,
    address: state.formData.address,
    images: state.formData.uploadimg,
  }
  sheep.$api.visit_record.postVisitRecordAdd(parpam).then((res) => {
     sheep.$helper.toast(res.msg)
    setTimeout(function () {
      sheep.$router.back(true)
      }, 500);
		});
  },1000)

};

// 删除图片
const deletePic = (event) => {
  state.fileList1.splice(event.index, 1);
  postData.value.splice(event.index, 1);
};

// 新增图片
const imageUpload = async (event) => {
  let lists = [].concat(event.file);
  let fileListLen = state.fileList1.length;
  lists.map((item) => {
    state.fileList1.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const url = await uploadFilePromise(lists[i].url, 'ugc');
    // console.log( url,'cccc')
    let item = state.fileList1[fileListLen];
    state.fileList1.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: sheep.$url.cdn(url),
    });
    fileListLen++;
  }

};
const postData = ref([])
async function uploadFilePromise(tempUrl) {
  let { url } = await sheep.$api.app.upload(tempUrl, 'ugc');
  postData.value.push(url)
  // state.fileList1.push(url)
  // console.log( state.fileList1, postData.value,'数组图片')
  return url;
};

  //删除 (展示模态窗)
const delete_show = ref(false)
const deletesubmit = ()=>{
  delete_show.value = true
}

// 删除按钮（确定）
const delete_confirm = () => {
  uni.$u.throttle(() => {
    let parpam = {
      ids :editid.value
    }
    sheep.$api.visit_record.postVisitRecordDelete(parpam).then((res) => {
      if(res.code == 1){
          uni.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1000
          })
          setTimeout(function() {
          sheep.$router.back(true)
            }, 500);
          
        }else{
          uni.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1000
          })
        }
      },1000)
    })
}

  // 删除按钮（取消）
  const delete_cancel = () => {
    delete_show.value = false
  }

//修改
const editsubmit = async() =>{
  state.formData.uploadimg = postData.value.join(',')
  const validate = await unref(relRef)
    .validate()
    .catch((error) => {
    });
  if (!validate) return;
  if (state.fileList1 == '') {
		uni.showToast({
			title: '请上传图片',
			icon: 'none',
			duration: 1000
		})
		return false
	}
  uni.$u.throttle(() => {
  let params={
    name:state.formData.realName,
    phone:state.formData.mobile,
    company:state.formData.company,
    content:state.formData.reason,
    address:state.formData.address,
    images:state.formData.uploadimg,
    ids:editid.value
  }
  sheep.$api.visit_record.postVisitRecordEdit(params).then((res) => {
    if(res.code == 1){
      sheep.$helper.toast(res.msg)
        setTimeout(function() {
          sheep.$router.back(true)
          }, 500);
        
      }else{
        sheep.$helper.toast(res.msg)
      }
		});
  },1000)
}

</script>

<style scoped lang="scss">
 @import '../compentns/public.scss';
//  修改内容
.edit_button{
    height: 144rpx;
    width: 90%;
    padding: 0 5%;
    background-color: #ffffff;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 98;
    display: flex;
    .del{width: 276rpx;
      height: 90rpx;
border-radius: 50rpx;
border: 2rpx solid $uni-color-primary;
color: $uni-color-primary;
 font-family: PingFangSC;
color: $uni-color-primary;
font-weight: $uni-font-weight;
font-size: 34rpx;}
.edit{
  margin-left: 20rpx;
  width: 354px;
height: 90rpx;
border-radius: 50rpx;
font-family: PingFangSC;
color: #FFFFFF;
font-weight: $uni-font-weight;
font-size: 34rpx;
background: linear-gradient(90deg, rgba(0, 56, 247, 1) 0%, rgba(77, 139, 255, 1) 100%);
}
}
// 滚动
.comprehensive{
        width: calc(100% - 40rpx);
        background-color: rgba(0, 0, 0, 0);
        margin: 0 20rpx;
        height: 65vh;
}
//图片
.cards {
  width: 100%;
  border-radius: 16rpx;
  background-color: #FFFFFF;
  margin-bottom: 120rpx;
  padding-bottom: 20rpx;
  .img{
    display: flex;
    margin-right: 10rpx;

  }
    :deep(.u-upload) {
      margin: 30rpx 0;
      width: 100% !important;
      background: #fff !important;
      .u-upload__wrap{
        flex-direction: row !important;
        flex-wrap: wrap !important;
        justify-content: flex-start !important;
      }
}

.uploadimg {
  width: 60rpx;
  height: 48rpx;
}
}
:deep(.u-upload__wrap__preview){
  margin: 0 4rpx 4rpx 0 !important;
  width: 140rpx !important;
  height: 140rpx !important;
}
</style>